package cn.hd01.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hd01.common.IntegrationRuleCode;
import cn.hd01.repository.IntegrationRepository;
import cn.hd01.repository.IntegrationRuleBookRepository;
import cn.hd01.repository.IntegrationRuleRepository;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.Dictionary;
import cn.hd01.repository.entity.Integration;
import cn.hd01.repository.entity.IntegrationRule;
import cn.hd01.repository.entity.IntegrationRuleBook;
import cn.hd01.service.CustomerService;
import cn.hd01.service.DictionaryService;
import cn.hd01.service.IntegrationRuleBookService;
import cn.hd01.sms.SmsService;
import cn.hd01.util.DictionaryType;

@Service
public class IntegrationRuleBookServiceImpl extends BaseServiceImpl<IntegrationRuleBook, Integer> implements IntegrationRuleBookService {

	@Autowired
	private IntegrationRuleRepository integrationRuleRepository; 
	
	private IntegrationRuleBookRepository repository;
	
	@Autowired
	private IntegrationRepository integrationRepository;
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	public IntegrationRuleBookServiceImpl(IntegrationRuleBookRepository repository) {
		super(repository);
		this.repository = repository;
	}
	
	@Override
	@Transactional
	public IntegrationRuleBook save(IntegrationRuleBook integrationRuleBook, IntegrationRuleCode code){
		IntegrationRule rule = integrationRuleRepository.findByRuleCode(code.getRuleCode());
		
		Integer customerId = integrationRuleBook.getCustomerId();
		if(rule != null){
			//后台修改的积分初始化好传进来的
			if(IntegrationRuleCode.CONSUME_INTEGRATION.equals(code)){
				integrationRuleBook.setIntegration(rule.getIntegration().multiply(integrationRuleBook.getAmount()));
			}else if(integrationRuleBook.getIntegration() == null){
				integrationRuleBook.setIntegration(rule.getIntegration());	
			}
			
			integrationRuleBook.setRuleCode(rule.getRuleCode());
			integrationRuleBook.setRuleName(rule.getRuleName());
			Date date = new Date();
			integrationRuleBook.setCreateTime(date);
			integrationRuleBook.setUpdateTime(date);
			integrationRuleBook.setRuleId(rule.getId());
			integrationRuleBook.setIntegrationReason(code.getRuleName());
			
			BigDecimal changeIntegration = integrationRuleBook.getIntegration();
			
			Integration integration = integrationRepository.findByCustomerId(customerId);
			if(integration == null){
				integration = new Integration();
				integration.setCustomerId(customerId);
				integration.setCustomerName(integrationRuleBook.getCustomerName());
				integration.setIntegration(changeIntegration);
				integration.setUsedIntegration(BigDecimal.ZERO);
				integration.setCreateTime(date);
				integration.setUpdateTime(date);
				integrationRepository.save(integration);
				
				integrationRuleBook.setAfterIntegration(changeIntegration);
			}else{
				if(BigDecimal.ZERO.compareTo(changeIntegration) > 0){
					integrationRepository.updateUsedIntegration(changeIntegration.abs(), customerId);	
				}else{
					integrationRepository.updateIntegration(changeIntegration, customerId);
				}
				integrationRuleBook.setAfterIntegration(changeIntegration.add(integration.getIntegration()));
			}
			
			repository.save(integrationRuleBook);
			
			//计算星级
			Integration currentIntegration = integrationRepository.findByCustomerId(customerId); 
			BigDecimal currentIntegrate = currentIntegration.getIntegration();
			String startName = null;
			List<Dictionary> dictList = dictionaryService.findByType(DictionaryType.STAR_LEVEL);
			for (Dictionary dictionary : dictList) {
				String value = dictionary.getValue();
				String vues [] =value.split("-");
				if(vues.length > 1){
					BigDecimal start = new BigDecimal(vues[0]);
					BigDecimal end = new BigDecimal(vues[1]);
					if(start.compareTo(currentIntegrate) != 1 && currentIntegrate.compareTo(end) != 1){//小于等于
						startName = dictionary.getName();
						break;
					}else{
						continue;
					}
				}else{
					//最后一个
					startName = dictionary.getName();
					break;
				}
			}
			
			Customer customer = customerService.findOne(customerId);
			customer.setLevel(startName);
			customerService.save(customer);
			
			//积分变动提醒
			if(!IntegrationRuleCode.SIGN_INTEGRATION.equals(code)){
				if(IntegrationRuleCode.BACKEND_INTEGRATION.equals(code) || IntegrationRuleCode.RECOMM_CONSUME_INTEGRATION.equals(code)){
					//②积分变动提醒：尊贵的千郡顾客，您当前积分变动XX分。剩余积分XX分。祝您生活愉快！【这部分内容在会员详情&会员积分管理模块都要有】
					//【千郡医疗】温馨提示：尊敬的千郡会员，您当前积分增加/抵扣XX分。剩余可用积分XX分。如有任何疑问，请及时与您的服务顾问联系。祝您生活愉快！
					StringBuffer sb = new StringBuffer("千郡会员，您当前积分");
					if(changeIntegration.compareTo(BigDecimal.ZERO) > 0	){
						sb.append("增加");
					}else{
						sb.append("抵扣");
					}
					sb.append(changeIntegration.abs()).append("分。剩余可用积分").append(integrationRuleBook.getAfterIntegration().intValue()).append("分。如有任何疑问，请及时与您的服务顾问联系。祝您生活愉快！");
					smsService.sendFixTimeMsg(customer.getPhoneNo(), sb.toString());
					//smsService.sendMsg(UCPSmsService.useIntegral, customer.getPhoneNo(), integrationRuleBook.getIntegration().intValue() + "," + integrationRuleBook.getAfterIntegration().intValue());
				}else{
					//【千郡医疗】温馨提醒：尊敬的千郡会员，您好！您本次消费获得XXX积分，当前可用积分XX分。祝您生活愉快！
					StringBuffer sb = new StringBuffer("千郡会员，您好！您本次消费获得").append(integrationRuleBook.getIntegration().intValue()).append("积分，当前可用积分").append(integrationRuleBook.getAfterIntegration().intValue()).append("。祝您生活愉快！");
					smsService.sendFixTimeMsg(customer.getPhoneNo(), sb.toString());
					//smsService.sendMsg(UCPSmsService.gainIntegral, customer.getPhoneNo(), integrationRuleBook.getAmount() + "," + integrationRuleBook.getIntegration().intValue() + "," + integrationRuleBook.getAfterIntegration().intValue());
				}
			}
			
		}
		return integrationRuleBook;
	}

	@Override
	public int countTodayRule(Integer id, String ruleCode) {
		return repository.countTodayRule(id, ruleCode);
	}

	@Override
	public Page<IntegrationRuleBook> findAll(
			final IntegrationRuleBook integrationRuleBook, Pageable pageable) {
		if (integrationRuleBook == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<IntegrationRuleBook>() {
			@Override
			public Predicate toPredicate(Root<IntegrationRuleBook> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				if(integrationRuleBook.getCustomerId() != null){
						predicates.add(cb.equal(r.get("customerId").as(Integer.class), integrationRuleBook.getCustomerId()));
				}
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}
	
}
